import React from 'react';
import { TreeSelect } from 'antd';
import { getCategoryAll } from 'services/article';

const recursionData = (data, pid = 0) => {
  const result = [];
  data.forEach((item, index) => {
    if(item.pid === pid){
      const obj = {
        title: item.name,
        value: item.id,
        key: `${pid}-${index}`,
        children: recursionData(data, item.id)
      };
      result.push(obj);
    }
  });
  return result;
};

const renderTreeData = (data, isShow) => {
  let treeNodeArr = [];
  if(isShow){
    treeNodeArr.push({
      title: '根节点',
      value: '0',
      key: '0',
      children: recursionData(data, 0)
    });
  }else{
    treeNodeArr = recursionData(data, 0);
  }
  return treeNodeArr;
};

class ArticleCategory extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      value: props.val,
      data: []
    };
    this.onChange = this.onChange.bind(this);
  }

  componentDidMount(){
    getCategoryAll().then(result => {
      const data = (result && result.data) || [];
      this.setState({data});
    });
  }
  static getDerivedStateFromProps(nextProps) {
    return nextProps;
  }

  onChange (value){
    const { onExtraChange, onChange } = this.props;
    if(value){
      this.setState({value});
      onChange && onChange(value);
    }
    onExtraChange && onExtraChange();
  }

  render() {
    const { isShow = true } = this.props;
    const { data } = this.state;
    const treeData = renderTreeData(data, isShow);
    return (
      <TreeSelect
        showSearch
        style={{width: '100%'}}
        value={this.state.value}
        treeData={treeData}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="请选择类型"
        allowClear
        onChange={value => this.onChange(value)}
      />
    );
  }
}

export default ArticleCategory;